package com.qire.manhua.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.qire.antsbinder.dal.exception.DataAccessException;
import com.qire.antscore.annotation.DalExceptionObserve;
import com.qire.antscore.annotation.RouteMapping;
import com.qire.antsrouter.inject.Autowired;
import com.qire.common.constant.Navigation;
import com.qire.common.constant.Url;
import com.qire.common.inject.EventControllerInjector;
import com.qire.common.support.base.BaseFragment;
import com.qire.common.utils.ObserveBinderHelper;
import com.qire.common.utils.ToastHelper;
import com.qire.manhua.R;
import com.qire.manhua.controller.BookshelfFavoritesController;
import com.qire.manhua.databinding.FragmentBookshelfFavoritesBinding;
import com.qire.manhua.model.viewModel.impl.BookshelfFavoritesViewModel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 首页->书架->收藏夹
 */
@RouteMapping(path = Navigation.Fragment.BookshelfFavoritesFragment)
public class BookshelfFavoritesFragment extends BaseFragment<FragmentBookshelfFavoritesBinding> {

    @Autowired
    BookshelfFavoritesViewModel viewModel;

    @Autowired(injector = EventControllerInjector.class)
    BookshelfFavoritesController controller;

    @Override
    public int layoutRid() {
        return R.layout.fragment_bookshelf_favorites;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        registerObserver();
        FragmentBookshelfFavoritesBinding viewDataBinder = viewDataBinder(inflater, container);
        viewDataBinder.setBookshelfFavoritesViewModel(viewModel);

        viewModel.onAddition(controller);
        controller.onAddition(viewModel);

        return viewDataBinder.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();

        viewModel.loadCarouselData();
        viewModel.loadFavoritesData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unregisterObserver();
    }

    protected void registerObserver() {
        ObserveBinderHelper.callRegisterOfDalExceptionObserveBinder(this);
    }

    protected void unregisterObserver() {
        ObserveBinderHelper.callUnregisterOfDalExceptionObserveBinder(this);
    }

    @DalExceptionObserve(tags = Url.HomeBookshelfFavoritesComicList)
    public void fetchCommentDataExceptionHandle(DataAccessException e) {
        viewModel.refreshLayoutFinish(false);
        viewModel.refreshEmptyDataUI(true);

        ToastHelper.showToast(e.extraMsg);
    }

}
